package com.hyc.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hyc.cloud.entities.CommonResult;
import com.hyc.cloud.entities.Payment;
import com.hyc.cloud.exception.SentinelCustomerException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 这里是类说明.
 *
 * @className: RateLimitController
 * @author: hyc
 * @date: 2022-02-15 10:27
 */
@RestController
public class RateLimitController {

    /**
     * @SentinelResource 注解的使用
     * @title byResource
     * @author hyc
     * @date 2022/2/15 10:29
     * @param
     * @return com.hyc.cloud.entities.CommonResult
     */
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handleException")
    public CommonResult byResource() {
        return new CommonResult(200, "按资源名称限流测试OK", new Payment(2020L, "serial001"));
    }

    // 降级限流处理方法 自定义返回限流提示
    public CommonResult handleException(BlockException exception) {
        return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
    }

    /**
     * 客户自定义限流处理类测试方法
     * @title customerHandlerTest
     * @author hyc
     * @date 2022/2/15 11:01
     * @param
     * @return com.hyc.cloud.entities.CommonResult
     */
    @GetMapping("/customerHandlerTest")
    @SentinelResource(value = "customerHandlerTest" // 资源名
            // 自定义限流处理类
            , blockHandlerClass = SentinelCustomerException.class
            //自定义限流处理方法 必须设置为static的方法
            , blockHandler = "exceptionHandler")
    public CommonResult customerHandlerTest() {
        return new CommonResult(200,"客户自定义限流处理类测试方法 success");
    }

    /**
     * 规则持久化配置测试方法
     * @title persistence
     * @author hyc
     * @date 2022/2/15 15:35
     * @param
     * @return java.lang.String
     */
    @GetMapping("/persistence")
    public String persistence() {

        return "success persistence";
    }

    /**
     * 黑白名单控制(授权规则)测试方法
     * @title authRule
     * @author hyc
     * @date 2022/2/15 15:58
     * @param
     * @return java.lang.String
     */
    @GetMapping("/authRule")
    public String authRule() {

        return "success auth rule";
    }
}